import 'package:flutter/material.dart';
import 'dart:async';
import '../widges/ddl_detail_card.dart';
import '../models/ddl_item.dart';
import '../pages/ddl_detail_page.dart';
import '../app_data_manager.dart';
import '../pages/recycle_bin_page.dart';
import '../widges/ddl_list.dart';

/// 备忘录页面组件
class MemoPage extends StatefulWidget {
  const MemoPage({super.key});

  @override
  _MemoPageState createState() => _MemoPageState();
}

/// 备忘录页面状态组件
class _MemoPageState extends State<MemoPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  
  // 添加状态变量来跟踪拖动目标的状态
  bool _isTargetingUrgent = false;
  bool _isTargetingNonUrgent = false;
  String? _activeDropArea;

  // 添加定时器
  Timer? _timer;
  DateTime _now = DateTime.now();

  @override
  void initState() {
    super.initState();
    // 初始化数据并刷新页面
    AppDataManager().init().then((_) {
      setState(() {});
    });
    // 设置定时器，每分钟更新一次当前时间
    _timer = Timer.periodic(const Duration(minutes: 1), (timer) {
      setState(() {
        _now = DateTime.now();
      });
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 每次页面显示时刷新数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      AppDataManager().init().then((_) {
        if (mounted) {
          setState(() {});
        }
      });
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  // 计算剩余时间文本
  String _getRemainingTime(DateTime? deadline) {
    if (deadline == null) return '未设置';
    final Duration difference = deadline.difference(_now);
    if (difference.isNegative) return '已超时';
    final int hours = difference.inHours;
    final int minutes = difference.inMinutes % 60;
    if (hours > 24) {
      final int days = hours ~/ 24;
      final int remainingHours = hours % 24;
      return '还剩 $days 天 $remainingHours 小时';
    } else if (hours > 0) {
      return '还剩 $hours 小时 $minutes 分钟';
    } else {
      return '还剩 $minutes 分钟';
    }
  }

  // 对DDL列表进行排序
  List<DDLItem> _getSortedDDLs(List<DDLItem> items) {
    final List<DDLItem> sortedItems = List.from(items);
    sortedItems.sort((a, b) => (b.deadline ?? DateTime(2100)).compareTo(a.deadline ?? DateTime(2100)));
    return sortedItems;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      endDrawerEnableOpenDragGesture: false,
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            IconButton(
              icon: const Icon(Icons.delete_outline),
              onPressed: () async {
                // 等待回收站页面关闭后刷新数据
                await Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const RecycleBinPage(),
                  ),
                );
                // 只刷新活动DDL和回收站数据
                print('回收站页面关闭，开始刷新数据...');
                await AppDataManager().loadDDLList();
                await AppDataManager().loadDDLRecycle();
                if (mounted) {
                  setState(() {});
                  print('数据刷新完成');
                }
              },
            ),
            const Text('备忘录'),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () async {
              // 创建一个新的DDL对象，直接进入编辑模式
              final now = DateTime.now();
              final newDDL = DDLItem(
                title: '',
                startDate: now,  // 设置起始日期为当前时间
                deadline: now.add(const Duration(days: 1)),  // 设置截止日期为明天
                isUrgent: false,  // 默认添加到非紧急队列
              );
              
              // 直接打开编辑页面，不等待返回结果
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DDLDetailPage(
                    item: newDDL,
                    onUpdate: (updatedItem) async {
                      // 验证日期
                      if (updatedItem.startDate == null || updatedItem.deadline == null) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('起始日期和截止日期不能为空')),
                        );
                        return;
                      }

                      // 验证截止日期是否晚于起始日期
                      if (updatedItem.deadline!.isBefore(updatedItem.startDate!)) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('截止日期必须晚于起始日期')),
                        );
                        return;
                      }

                      // 只有当标题不为空时才保存
                      if (updatedItem.title.isNotEmpty) {
                        await AppDataManager().addDDL(updatedItem);
                        setState(() {});
                      }
                    },
                  ),
                ),
              );
            },
          ),
          IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () {
              _scaffoldKey.currentState?.openEndDrawer();
            },
          ),
          const SizedBox(width: 8),
        ],
      ),
      endDrawer: Align(
        alignment: Alignment.centerRight,
        child: Container(
          width: MediaQuery.of(context).size.width * 0.5,
          height: MediaQuery.of(context).size.height - kBottomNavigationBarHeight,
          color: Colors.white,
          child: Column(
            children: const [
              SizedBox(height: 40),
              Text('副导航栏', style: TextStyle(fontSize: 20)),
            ],
          ),
        ),
      ),
      body: _buildMainContent(),
    );
  }

  Widget _buildMainContent() {
    // 在build方法中获取数据
    final List<DDLItem> activeDdlItems = AppDataManager().getDDLList();
    
    return Column(
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: _buildDDLColumn(
                  '急急国王',
                  activeDdlItems.where((item) => item.isUrgent).toList(),
                ),
              ),
              Expanded(
                child: _buildDDLColumn(
                  '你看，又急',
                  activeDdlItems.where((item) => !item.isUrgent).toList(),
                ),
              ),
            ],
          ),
        ),
        _buildBottomActions(),
      ],
    );
  }

  /// 构建DDL的两个状态列
  Widget _buildDDLColumn(String title, List<DDLItem> items) {
    final sortedItems = _getSortedDDLs(items);
    
    return DragTarget<DDLItem>(
      onWillAcceptWithDetails: (item) {
        print('onWillAccept: $item');
        setState(() {
          if (title == '急急国王') {
            _isTargetingUrgent = true;
          } else {
            _isTargetingNonUrgent = true;
          }
        });
        return true;
      },
      onLeave: (item) {
        print('onLeave: $item');
        setState(() {
          if (title == '急急国王') {
            _isTargetingUrgent = false;
          } else {
            _isTargetingNonUrgent = false;
          }
        });
      },
      onAcceptWithDetails: (item) async {
        print('onAccept: $item');
        // 如果是回收站的卡片
        if (item.data.isCompleted || item.data.isAbandoned) {
          await AppDataManager().removeFromRecycleBin(item.data);
          item.data.isCompleted = false;
          item.data.isAbandoned = false;
          item.data.isUrgent = title == '急急国王';
          await AppDataManager().addToDDL(item.data);
          // 回收站拖回，统计-1
          final now = DateTime.now();
          final date = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
          if (item.data.isCompleted) {
            await AppDataManager().updateGoalStats(date, 'completed', -1);
          } else if (item.data.isAbandoned) {
            await AppDataManager().updateGoalStats(date, 'abandoned', -1);
          } else {
            await AppDataManager().updateGoalStats(date, 'cancelled', -1);
          }
        } else {
          // 如果是队列切换
          await _switchQueue(item.data, title == '急急国王');
          }
        setState(() {
          if (title == '急急国王') {
            _isTargetingUrgent = false;
          } else {
            _isTargetingNonUrgent = false;
          }
        });
      },
      builder: (context, candidateData, rejectedData) {
        final bool isTargeting = title == '急急国王' ? _isTargetingUrgent : _isTargetingNonUrgent;
        
        return AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          transform: isTargeting 
              ? Matrix4.diagonal3Values(1.05, 1.05, 1.0)
              : Matrix4.identity(),
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                color: isTargeting ? Colors.blue[200] : Colors.blue[100],
                child: Text(
                  title,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: isTargeting ? Colors.blue[50] : null,
                    border: isTargeting 
                        ? Border.all(color: Colors.blue, width: 2)
                        : null,
                  ),
                  child: ListView.builder(
                    itemCount: sortedItems.length,
                    itemBuilder: (context, index) {
                      return _buildDraggableDDLCard(sortedItems[index]);
                    },
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建可拖拽的DDL卡片组件
  Widget _buildDraggableDDLCard(DDLItem item) {
    return LongPressDraggable<DDLItem>(
      data: item,
      feedback: Material(
        elevation: 8,
        borderRadius: BorderRadius.circular(8),
        child: Container(
          width: MediaQuery.of(context).size.width * 0.4,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                blurRadius: 8,
                spreadRadius: 1,
              ),
            ],
          ),
          child: Text(item.title),
        ),
      ),
      child: DDLDetailCard(
        item: item,
        isInRecycleBin: false,
        onTap: () => _openDDLDetail(item),
      ),
    );
  }

  Widget _buildBottomActions() {
    return Container(
      height: 100,
      color: Colors.grey[200],
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildDropTarget('完成啦！', Colors.green, (item) async {
            await _completeDDL(item);
          }),
          _buildDropTarget('这个活动取消啦！', Colors.orange, (item) async {
            await _cancelDDL(item);
          }),
          _buildDropTarget('不干了！', Colors.red, (item) async {
            await _abandonDDL(item);
          }),
        ],
      ),
    );
  }

  Widget _buildDropTarget(
    String label,
    Color color,
    Function(DDLItem) onAccept,
  ) {
    return DragTarget<DDLItem>(
      onWillAcceptWithDetails: (data) {
        setState(() {
          _activeDropArea = label;
        });
        return true;
      },
      onLeave: (data) {
        setState(() {
          _activeDropArea = null;
        });
      },
      onAcceptWithDetails: (item) async {
        await onAccept(item.data);
        // 拖拽到完成/取消/放弃区域时，统计+1
        final now = DateTime.now();
        final date = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
        if (label == '完成啦！') {
          await AppDataManager().updateGoalStats(date, 'completed', 1);
        } else if (label == '这个活动取消啦！') {
          await AppDataManager().updateGoalStats(date, 'cancelled', 1);
        } else if (label == '不干了！') {
          await AppDataManager().updateGoalStats(date, 'abandoned', 1);
        }
        setState(() {
          _activeDropArea = null;
        });
      },
      builder: (context, candidateData, rejectedData) {
        final bool isTargeting = _activeDropArea == label;
        
        return AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          width: isTargeting ? 120 : 100,
          height: isTargeting ? 100 : 80,
          decoration: BoxDecoration(
            color: color.withOpacity(isTargeting ? 0.3 : 0.2),
            borderRadius: BorderRadius.circular(8),
            border: Border.all(
              color: color,
              width: isTargeting ? 3 : 2,
            ),
            boxShadow: isTargeting
                ? [
                    BoxShadow(
                      color: color.withOpacity(0.3),
                      blurRadius: 8,
                      spreadRadius: 2,
                    ),
                  ]
                : null,
          ),
          child: Center(
            child: AnimatedDefaultTextStyle(
              duration: const Duration(milliseconds: 200),
              style: TextStyle(
                color: color,
                fontWeight: FontWeight.bold,
                fontSize: isTargeting ? 18 : 16,
              ),
              child: Text(
                label,
                textAlign: TextAlign.center,
              ),
            ),
          ),
        );
      },
    );
  }

  void _openDDLDetail(DDLItem item) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => DDLDetailPage(
          item: item,
          onUpdate: (updatedItem) async {
            await AppDataManager().updateDDL(updatedItem);
            setState(() {});
          },
        ),
      ),
    );
  }

  Future<void> _completeDDL(DDLItem item) async {
    // 更新DDL状态
    item.isCompleted = true;
    await AppDataManager().updateDDL(item);
    await AppDataManager().addToRecycleBin(item);
    await AppDataManager().removeFromDDL(item);
    // 不再在这里更新统计数据
    setState(() {});
  }

  Future<void> _cancelDDL(DDLItem item) async {
    // 更新DDL状态
    item.isCompleted = false;
    await AppDataManager().updateDDL(item);
    await AppDataManager().addToRecycleBin(item);
    await AppDataManager().removeFromDDL(item);
    // 不再在这里更新统计数据
    setState(() {});
  }

  Future<void> _abandonDDL(DDLItem item) async {
    // 更新DDL状态
    item.isCompleted = false;
    item.isAbandoned = true;  // 设置放弃状态
    await AppDataManager().updateDDL(item);
    await AppDataManager().addToRecycleBin(item);
    await AppDataManager().removeFromDDL(item);
    // 不再在这里更新统计数据
    setState(() {});
  }

  // 处理队列切换
  Future<void> _switchQueue(DDLItem item, bool isUrgent) async {
    print('开始切换队列...');
    print('原DDL: ${item.toJson()}');
    
    // 创建新的DDL对象，保持其他属性不变
    final updatedItem = item.copyWith(
      pid: item.pid,  // 保持原有的pid
      isUrgent: isUrgent,
    );
    print('更新后的DDL: ${updatedItem.toJson()}');
    
    // 更新到AppDataManager
    await AppDataManager().updateDDL(updatedItem);
    
    // 刷新页面状态
    setState(() {});
    print('队列切换完成');
  }
}

